package com.haoxuer.discover.workflow.controller.admin;

import com.haoxuer.discover.workflow.data.service.FlowDefineService;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.data.page.Page;
import com.haoxuer.discover.data.page.Pageable;
import com.haoxuer.discover.data.utils.FilterUtils;
import com.haoxuer.discover.workflow.data.entity.FlowDefine;
import com.haoxuer.discover.workflow.data.so.FlowDefineSo;
import java.io.StringReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.bpmn.model.StartEvent;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * Created by imake on 2018年01月08日14:52:01.
 */


@Scope("prototype")
@Controller
public class FlowDefineAction {
  
  public static final String MODEL = "model";
  
  public static final String REDIRECT_LIST_HTML = "redirect:/admin/flowdefine/view_list.htm";
  
  private static final Logger log = LoggerFactory.getLogger(FlowDefineAction.class);
  
  @Autowired
  private FlowDefineService manager;
  
  @Autowired
  private RepositoryService repositoryService;
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/view_list")
  public String list(Pageable pageable, FlowDefineSo so, ModelMap model) {
    
    if (pageable == null) {
      pageable = new Pageable();
    }
    if (pageable.getOrders().isEmpty()) {
      pageable.getOrders().add(Order.desc("id"));
    }
    pageable.getFilters().addAll(FilterUtils.getFilters(so));
    Page<FlowDefine> pagination = manager.page(pageable);
    model.addAttribute("list", pagination.getContent());
    model.addAttribute("page", pagination);
    model.addAttribute("so", so);
    return "/admin/flowdefine/list";
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/view_add")
  public String add(ModelMap model) {
    
    BpmnModel bpmnModel = new BpmnModel();
    Process process = new Process();
    process.setName("流程名称");
    bpmnModel.addProcess(process);
    process.addFlowElement(createStartEvent());
    process.addFlowElement(createEndEvent());
    process.addFlowElement(createSequenceFlow("start", "end"));
    
    process.setId("my-process");
    BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
    
    byte[] convertToXML = bpmnXMLConverter.convertToXML(bpmnModel);
    
    String bytes = new String(convertToXML);
    
    model.addAttribute("content", bytes);
    return "/admin/flowdefine/add";
  }
  
  protected SequenceFlow createSequenceFlow(String from, String to) {
    SequenceFlow flow = new SequenceFlow();
    flow.setSourceRef(from);
    flow.setTargetRef(to);
    return flow;
  }
  
  
  protected StartEvent createStartEvent() {
    StartEvent startEvent = new StartEvent();
    startEvent.setId("start");
    return startEvent;
  }
  
  //创建task
  protected UserTask createUserTask(String id, String name, String assignee) {
    UserTask userTask = new UserTask();
    userTask.setName(name);
    userTask.setId(id);
    userTask.setAssignee(assignee);
    return userTask;
  }
  
  protected static EndEvent createEndEvent() {
    EndEvent endEvent = new EndEvent();
    endEvent.setId("end");
    return endEvent;
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/view_edit")
  public String edit(Pageable pageable, Long id, ModelMap model) {
    model.addAttribute(MODEL, manager.findById(id));
    model.addAttribute("page", pageable);
    return "/admin/flowdefine/edit";
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/view_view")
  public String view(Long id, ModelMap model) {
    model.addAttribute(MODEL, manager.findById(id));
    return "/admin/flowdefine/view";
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/model_save")
  public String save(FlowDefine bean, ModelMap model) {
    
    String view = REDIRECT_LIST_HTML;
    try {
      manager.save(bean);
      log.info("save object id={}", bean.getId());
    } catch (Exception e) {
      log.error("保存失败", e);
      model.addAttribute("erro", e.getMessage());
      view = "/admin/flowdefine/add";
    }
    return view;
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/deploy")
  public String deploy(Long id, ModelMap model) {
    
    String view = REDIRECT_LIST_HTML;
    try {
      FlowDefine flow = manager.findById(id);
      BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
      XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
      XMLStreamReader reader = xmlFactory.createXMLStreamReader(new StringReader(flow.getContent()));
      BpmnModel bpmnModel = bpmnXMLConverter.convertToBpmnModel(reader);
      Deployment deployment = repositoryService.createDeployment()
          .addBpmnModel("dynamic-model.bpmn", bpmnModel).name(flow.getName())
          .deploy();
    } catch (Exception e) {
      log.error("部署失败", e);
      model.addAttribute("erro", e.getMessage());
    }
    return view;
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/model_update")
  public String update(Pageable pageable, FlowDefine bean, RedirectAttributes redirectAttributes, ModelMap model) {
    
    String view = REDIRECT_LIST_HTML;
    try {
      manager.update(bean);
      initRedirectData(pageable, redirectAttributes);
    } catch (Exception e) {
      log.error("更新失败", e);
      model.addAttribute("erro", e.getMessage());
      model.addAttribute(MODEL, bean);
      model.addAttribute("page", pageable);
      view = "/admin/flowdefine/edit";
    }
    return view;
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/model_delete")
  public String delete(Pageable pageable, Long id, RedirectAttributes redirectAttributes) {
    
    String view = REDIRECT_LIST_HTML;
    
    try {
      initRedirectData(pageable, redirectAttributes);
      manager.deleteById(id);
    } catch (DataIntegrityViolationException e) {
      log.error("删除失败", e);
      redirectAttributes.addFlashAttribute("erro", "该条数据不能删除，请先删除和他相关的类容!");
    }
    
    return view;
  }
  
  @RequiresPermissions("flowdefine")
  @RequestMapping("/admin/flowdefine/model_deletes")
  public String deletes(Pageable pageable, Long[] ids, RedirectAttributes redirectAttributes) {
    
    String view = REDIRECT_LIST_HTML;
    
    try {
      initRedirectData(pageable, redirectAttributes);
      manager.deleteByIds(ids);
    } catch (DataIntegrityViolationException e) {
      log.error("批量删除失败", e);
      redirectAttributes.addFlashAttribute("erro", "该条数据不能删除，请先删除和他相关的类容!");
    }
    return view;
  }
  
  private void initRedirectData(Pageable pageable, RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("pageNumber", pageable.getPageNumber());
  }
}